
const batteryServiceUUID = 'battery_service';
const batteryCharacteristicUUID = 'battery_level';

const serviceUUID = '7f04f3f0-b665-11e3-a5e2-0800200c9a66';
const readCharacteristicUUID = '7d32c0f0-bef5-11e3-b1b6-0800200c9a66';
const writeCharacteristicUUID = "92b403f0-b665-11e3-a5e2-0800200c9a66";

const START_COMMAND = "0009FFFF0101000000000000000000000009";
const STOP_COMMAND = "001BFFFF010000000000000000000000001A";

var result;
var mierDevices = [];
var batteryService;
var batteryChar;

//window.onload = function(){
//  document.querySelector('#discover').addEventListener('click', discover);
//};

function discover(filter) {
  if (!navigator.bluetooth) {
      log('Web Bluetooth API is not available.\n' +
          'Please make sure the Web Bluetooth flag is enabled.');
      return;
  }
  log('\nRequesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({
    filters: [
      {services: [serviceUUID]},
      // { namePrefix: 'SO-' }
    ]
    // ,optionalServices:[batteryServiceUUID]
  })
  .then(device => {
    log("开始连接设备：" + device.name);
    addDevice(device);
    connect(device);
  })
  .catch(error => {
    log('* connect ' + error);
  });
}

function connect(device) {
  console.log("将要连接的设备：", device);
  if(!device.gatt.connected) {
    log("设备确实没有连接");
    device.addEventListener('gattserverdisconnected', onDisconnected);
    device.gatt.connect()
    .then(server => {
      console.log('Got bleServer:', server);
      if(!server.connected) {
        log("请重新配对");
      }
      return server.getPrimaryService(serviceUUID);
    })
    .catch(error => {
      log('设备已断开，请重新配对 ');
    })
    .then(service => {
      console.log("Got service:", service);
      log("连接到的service UUID为：" + serviceUUID);
      service.getCharacteristic(writeCharacteristicUUID)
      .then( characteristic => {
        testStart(characteristic);
       // renderTable();
      })
      service.getCharacteristic(readCharacteristicUUID)
      .then( characteristic => {
        console.log('start notification reading characteristic: ', characteristic);
        log("监听的characteristic UUID为：" + readCharacteristicUUID);
        characteristic.startNotifications();
        characteristic.addEventListener('characteristicvaluechanged',  handleCharacteristicValueChanged);
        return characteristic.readValue();
      })
      .catch(error => {
        log('* connect ' + error);
      });
      // listening(service);
    });
  } else {
    log("设备已经是连接状态");
  } 
}

function listening(service) {
  console.log("Got service:", service);
  log("连接到的service UUID为：" + serviceUUID);
  service.getCharacteristic(writeCharacteristicUUID)
  .then( characteristic => {
    console.log('开始 writing characteristic: ', characteristic);
    log("可写的characteristic UUID：" + writeCharacteristicUUID);
    testStart(characteristic);
  })

  .then(() => service.getCharacteristic(readCharacteristicUUID))
  .then(characteristic2 => {
    console.log('开始 notification reading characteristic: ', characteristic2);
    log("监听的characteristic UUID为：" + readCharacteristicUUID);
    characteristic2.startNotifications();
    characteristic2.addEventListener('characteristicvaluechanged',  handleCharacteristicValueChanged);
    return characteristic2.readValue();
  })
}

function getDevice(deviceName) {
  for(let i=0; i < mierDevices.length; i++) {
    if(mierDevices[i].name == deviceName) {
      return mierDevices[i];
    }
  }
}

function reConnect(deviceName) {
  log("重新连接设备:" + deviceName);
  disconnect(deviceName);
  if (!deviceName) {
    log('该设备未连接...');
    return;
  }
  let device = getDevice(deviceName);
  if(device) {
    disconnectDevice(device);
    // connect(device);
  } else {
    alert("找不到设备，请重新配对");
  }
}

function disconnectDevice(device) {
  if(device.gatt.connected) {
    device.gatt.disconnect();
    log(' 现在该设备的连接状态是 : ' + device.gatt.connected);
  } else {
    log(' 该设备已经是断开状态的。');
  }
}

function disconnect(deviceName) {
  console.log("将要断开连接的设备：", deviceName);
  if (!deviceName) {
    log('该设备未连接...');
    return;
  }
  let device = getDevice(deviceName);
  if(device.name == deviceName) {
    if(device.gatt.connected) {
      device.gatt.disconnect();
      log(' 现在该设备的连接状态是 : ' + device.gatt.connected);
    } else {
      log(' 该设备已经是断开状态的。');
    }
  }
  //renderTable();
}

function addDevice(device) {
  console.log("新加入到设备列表：", device);
  if (mierDevices.indexOf(device) === -1) {
    mierDevices.push(device);
  }
}

function getBatteryLevel() {
  bleServer.getPrimaryService(batteryServiceUUID)
  .then(service => {
    console.log("Got battery service:", service);
    batteryService = service;
    return batteryService.getCharacteristic(batteryCharacteristicUUID);
  })
  .then( characteristic => {
    console.log('Got battery characteristic: ', characteristic);
    batteryChar = characteristic;
    // return batteryChar.addEventListener('characteristicvaluechanged',  handleBatteryLevelChanged);
    return batteryChar.readValue();
  })
  .then(value => {
    let batteryLevel = value.getUint8(0);
    log('> Battery Level is ' + batteryLevel + '%');
  })
  .catch(error => {
    log('* Argh! ' + error);
  });
}


/* This function will be called when `readValue` resolves and
 * characteristic value changes since `characteristicvaluechanged` event
 * listener has been added. */
function handleBatteryLevelChanged(event) {
  let value = event.target.value.getUint8(0);
  log('> The Battery Level is: ' + value + '%');
  document.getElementById("battery-level").innerHTML = "当前电量：" + value + '%';
}

function handleCharacteristicValueChanged(event) {
  let value = new Uint8Array(event.target.value.buffer);
  log('> 读取蓝牙数据 : ' + value);
  let result = getResult(event);
  console.log(result);
}

function testStop(char) {
  log("给写入通道发送停止指令。");
  let command = Uint8Array.of(STOP_COMMAND);
  char.writeValue(command)
  .then(_ => {
    log('<< 停止测试了 >>');
  })
  .catch(error => {
    log('Argh, stop failed! ' + error);
  });
}

function testStart(char) {
  log("给写入通道发送启动指令。");
  let command = Uint8Array.of(START_COMMAND);
  char.writeValue(command)
  .then(_ => {
    log('<< 现在可以开始测试了 >>');
  })
  .catch(error => {
    log('Argh, start failed! ' + error);
  });
}

function testRestart(char) {
  log("重新启动测试：" + char.uuid);
  listening(char.service);
}

function log(text) {
    console.log(text);
    //document.querySelector('#log').textContent += text + '\n';
}

function getResult(event) {
  let data = new Uint8Array(event.target.value.buffer);
  let sum = 0;
  for(let k = 0; k <= 16; ++k) {
      sum += data[k] & 255;
  }

  if ((sum % 256) == data[17]) {
      let flow;
      let i;
      switch(data[1]) {
      case 209:
          i = (data[9] & 255) * 256 + (data[10] & 255);
          flow = (data[7] & 255) * 256 + (data[8] & 255);
          let quality = (data[5] & 255) * 256 + (data[6] & 255);
          let eVol = (data[11] & 255) * 256 + (data[12] & 255);
          let pefTime = (data[13] & 255) * 256 + (data[14] & 255);
          log("pef:" + flow);
          log("fev1:" + i);
          let testValue = {
            deviceName: event.target.service.device.name,
            pef: flow,
            fev1: i
          }
          result = testValue;
          // console.log(event.target);
          return [flow, i];
      case 9:
          if (data[2] == -1 & data[3] == -1) {
              reConnect(event.target.service.device.name);
              return;
          }

          for(i = 5; i < 17; i = i + 2) {
              flow = (data[i] & 255) * 256 + (data[i + 1] & 255);
              if (flow >= 32768) {
                flow = flow - 65536;
              }
              // bleDevice.flowUpdated((fev1));
          }

          return [flow, i];
      case 27:
        reConnect(event.target.service.device.name);
        break;
      // case 28:
      //   event.target.service.getCharacteristic(writeCharacteristicUUID)
      //   .then( characteristic => {
      //     testStop(characteristic);
      //   })
      //   break;
      }
  }
}

function onDisconnected(event) {
  const device = event.target;
  setTimeout(() => connect(device), 2000);
}

function renderTable() {
  console.log("有新设备添加，重新加载列表", mierDevices);
  let data = [];
  for (var i = 0; i < mierDevices.length; i++) {
    data.push({
      id:mierDevices[i].id,
      name:mierDevices[i].name,
      connected:mierDevices[i].gatt.connected});
  }

  console.log("表格将要加载的元数据：", data);
  $('#table').bootstrapTable('destroy').bootstrapTable({
    data: data,
    columns: [
      /* 前面 勾选框
      {
        field : 'ids',
        checkbox : true
      }, */
      {
        field : 'name',
        title : '名称',
        align : 'center'
      },
      {
        field : 'connected',
        title : '状态',
        align : 'center',
        formatter:function(value,row,index){ 
          var value="";
          if(row.connected == true){
            value = "已连接";
          } else {
            value = "未连接";
          }
          return value;
        }
      },
      {
        field : 'id',
        title : '操作',
        align : 'center',
        formatter : function(value, row, index) {
          var c = '<a class="green-color" href="#" onclick="reConnect(\'' + row.name + '\')">重新连接</a> ';
          var d = '<a class="green-color" href="#" onclick="disconnect(\'' + row.name + '\')"> 重新连接</a> ';
          return d ;
        }
      }, ]
  })
}
